<template>
  <portal
    ref="tableRef"
    :action-width="120"
    :default-sort-column="[{property: 'updateAt', type: 1}]"
    :readOnly="readOnlySupportRole()"
    :row-allow-delete="rowAllowDelete"
    :row-allow-edit="rowAllowEdit"
    table-id="order">
    <template #action="{ record }">
      <div style="display: flex; justify-content: space-around">
        <template v-for="op in operations" :key="op.label">
          <a-button
            v-if="operationSupportOrderStatus(op, record) && operationSupportRole(op)"
            type="link" @click="operate(record, op.value)">
            {{ op.label }}
          </a-button>
        </template>
      </div>
    </template>
  </portal>
</template>

<script lang="ts" setup>
import {useUserStore} from '@/framework/store/user'
import pinia from '@/framework/store'
import {ORDER_OPERATOR_STATUS, TANYA_ROLE_ID} from '@/constant/dict'
import {getOrderFsmConfig, orderOperate} from '@/apis/order'

const tableRef = ref()
const operations = ref([] as Array<any>)
const init = () => {
  getOrderFsmConfig().then((resp) => {
    operations.value = resp.payload || []
    console.log(operations.value)
  })
}

const _log = (arg: any) => console.log(arg)

const userStore = useUserStore(pinia)
const operate = (record: any, operate: string) => {
  orderOperate(record.id, operate).then(tableRef.value.queryData)
}
const rowAllowEdit = (record: any) => {
  return record.operationStatus === ORDER_OPERATOR_STATUS.DRAFT
}
const rowAllowDelete = () => {
  return false
}
const operationSupportOrderStatus = (op: any, record: any) => {
  return op.supportStatusList.indexOf(record.operationStatus) !== -1
}
const operationSupportRole = (op: any) => {
  const roleList = userStore.getRole || []
  let res = false
  for (let role of roleList) {
    res = res || op.supportRoleList.indexOf(String(role)) !== -1
  }
  return res
}
const readOnlySupportRole = () => {
  const roleList = userStore.getRole || []
  return roleList.indexOf(TANYA_ROLE_ID.TRADER as never) === -1
}
onMounted(() => {
  init()
})
</script>

<style scoped>

</style>
